﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace HamcoWcs.Models.Devices
{
    public class GlobalMonitor
    {
        public GlobalMonitor()
        {

        }
        public PconPlc Plc { get; set; }
        public List<RasterDto> Rasters { get; set; }

        private byte[] buffer;

        public bool SetRasterBypass(string rasterName)
        {
            var raster = Rasters.FirstOrDefault(x => x.Name == rasterName);
            if (raster == null) return false;
            if (!Plc.ConnectionStatus) Plc.ConnectToPlc();
            if (!Plc.ConnectionStatus) return false;
            return raster.SetBypass(Plc.Client);
        }

        public void Update()
        {
            if (!Plc.ConnectionStatus) Plc.ConnectToPlc();
            if (!Plc.ConnectionStatus) return;

            var dbInfo = Plc.DbInfo.FirstOrDefault(x => x.DbName.Equals("other_recv", StringComparison.OrdinalIgnoreCase));
            if (dbInfo == null) throw new Exception("未找到other_recv的DB信息");

            var recv = new byte[dbInfo.DbLength];

            int res = 0;
            lock (Plc.Client)
            {
                res = Plc.Client.DBRead(dbInfo.DbNum, dbInfo.StartPoint, dbInfo.DbLength, recv);
            }
            if (res != 0)
            {
                return;
                //Plc.DisconnectToPlc();
                //throw new Exception($"{Plc.PlcName}接受[DB{dbInfo.DbNum}]失败");
            }
            buffer = recv;

            // 更新安全光栅的状态
            foreach (var raster in Rasters)
            {
                raster.UpdateRecv(buffer);
            }
        }

    }
}
